package com.why.biyesheji.service.impl;

import com.fasterxml.jackson.databind.util.BeanUtil;
import com.why.biyesheji.common.Constants;
import com.why.biyesheji.common.ServiceResultEnum;
import com.why.biyesheji.common.TokenCache;
import com.why.biyesheji.dao.UserMapper;
import com.why.biyesheji.pojo.User;
import com.why.biyesheji.service.ICartService;
import com.why.biyesheji.service.IUserService;
import com.why.biyesheji.util.MD5Util;
import com.why.biyesheji.util.ResultGenerator;
import com.why.biyesheji.vo.MallUserVO;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpSession;
import java.lang.reflect.InvocationTargetException;
import java.util.List;
import java.util.UUID;

/**
 * Created by 华耀 王 on 2020/10/13
 **/
//@Component
@Service("iUserService")
public class UserServiceImpl implements IUserService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private ICartService iCartService;

    //登录模块
    public String login(String username,String password, HttpSession httpSession){
        //验证用户名是否存在
        int resultCount = userMapper.checkUsername(username);
        if (resultCount == 0){
            return ServiceResultEnum.LOGIN_NAME_NOTEXIST.getResult();
        }
        User user = userMapper.login(username,password);
        if (user == null){
            return ServiceResultEnum.LOGIN_PASSWORD_ERROR.getResult();
        }
        if(user.getUsername() != null && user.getUsername().length() > 7){
            //.substring(0,7)截取下标0-6的值，不包括7
            String tempUsername = user.getUsername().substring(0,7) + "..";
            user.setUsername(tempUsername);
        }
        MallUserVO mallUserVO = new MallUserVO();
        try {
            BeanUtils.copyProperties(mallUserVO,user);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
            return ServiceResultEnum.ERROR.getResult();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
            return ServiceResultEnum.ERROR.getResult();
        }
        // 购物车的数量功能,查询购物车表商品数量
        int cart_count = iCartService.cart_count(mallUserVO.getId());
        mallUserVO.setCartItemCount(cart_count);
        httpSession.setAttribute(Constants.MALL_USER_SESSION_KEY,mallUserVO);

        // 安全性，将查询到的密码设置为空
        user.setPassword(StringUtils.EMPTY);
        return ServiceResultEnum.SUCCESS.getResult();
    }

//    异步查询用户名是否存在
    public String check_username(String username){
        int resultCount = userMapper.checkUsername(username);
        if (resultCount > 0){
            return ServiceResultEnum.REGISTER_NAME_EXIST.getResult();
        }
        return ServiceResultEnum.SUCCESS.getResult();
    }

    //注册模块
    public String register(String username,String password,String phone,String email,
                           String question,String answer){
        String MD5Password = MD5Util.MD5EncodeUtf8(password);
        User user = new User();
        user.setUsername(username);
        user.setPassword(MD5Password);
        user.setPhone(phone);
        user.setEmail(email);
        user.setQuestion(question);
        user.setAnswer(answer);
        int resultRegister = userMapper.insert(user);
        if (resultRegister == 0){
            return ServiceResultEnum.ERROR.getResult();
        }
        return ServiceResultEnum.SUCCESS.getResult();
    }

    //    获取用户的密码问题
    public String forget_get_question(String username){
        int resultUsername = userMapper.checkUsername(username);
        if (resultUsername == 0){
            return ServiceResultEnum.LOGIN_NAME_NOTEXIST.getResult();
        }
        String resultCount = userMapper.selectQuestion(username);
        if (resultCount == null){
            return "用户设置的问题为空";
        }
        return resultCount;
    }

    //    获取用户的密码答案
    public String forget_check_answer(String username,String question,String answer){
        int resultCount = userMapper.checkAnswer(username,question,answer);
        //如果大于零说明答案是属于此用户的，且验证成功
        if (resultCount > 0){
            String forgetToken = UUID.randomUUID().toString();
            //把forgetToken（忘记密码令牌）放到本地cache，设置有效期
            TokenCache.setKey(TokenCache.TOKEN_PREFIX+username,forgetToken);
            return forgetToken;
        }
        return "false";
    }

    //    重设用户密码
    public String forgetResetPassword(String username,String passwordNew,String forgetToken){
        if (StringUtils.isBlank(forgetToken)){
            return "参数错误，token需要传递！";
        }
        int resultUsername = userMapper.checkUsername(username);
        if (resultUsername == 0){
            return ServiceResultEnum.LOGIN_NAME_NOTEXIST.getResult();
        }

        String token = TokenCache.getKey(TokenCache.TOKEN_PREFIX+username);
        if (StringUtils.isBlank(token)){
            return "token无效或者过期";
        }

        if (StringUtils.equals(forgetToken,token)){
            String md5Password = MD5Util.MD5EncodeUtf8(passwordNew);
            int rowCount = userMapper.updatePasswordByUsername(username,md5Password);
            if (rowCount > 0){
                return "true";
            }
        }else{
            return "token错误，请重新获取重置密码的token";
        }
        return "修改密码失败";
    }

    //更新用户信息
    public String updateUserInfo(User user,HttpSession httpSession){
        MallUserVO userSession = (MallUserVO) httpSession.getAttribute(Constants.MALL_USER_SESSION_KEY);
        //防止横向越权（防止传来别人的id），这样我们的id和username都是从我们的session中获取的
        user.setId(userSession.getId());
        user.setUsername(userSession.getUsername());

        User updateUser = new User();
        updateUser.setId(user.getId());
        updateUser.setPhone(user.getPhone());
        updateUser.setEmail(user.getEmail());
        updateUser.setQuestion(user.getQuestion());
        updateUser.setAnswer(user.getAnswer());


        int userResult = userMapper.updateByPrimaryKeySelective(updateUser);
        if (userResult > 0){
            MallUserVO mallUserVO = new MallUserVO();
            try {
                BeanUtils.copyProperties(mallUserVO,updateUser);
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            } catch (InvocationTargetException e) {
                e.printStackTrace();
            }
            mallUserVO.setUsername(userSession.getUsername());
            mallUserVO.setCartItemCount(userSession.getCartItemCount());
            httpSession.setAttribute(Constants.MALL_USER_SESSION_KEY,mallUserVO);
            return ServiceResultEnum.SUCCESS.getResult();
        }
        return "个人信息修改错误";
    }

    //更新用户密码
    public String updateUserPass(String passwordOld,String passwordNew,MallUserVO mallUserVO){
        //防止横向越权，要校验是这个用户的并且旧密码正确
        int resultCount = userMapper.checkPassword(MD5Util.MD5EncodeUtf8(passwordOld),mallUserVO.getId());
        if (resultCount == 0){
            return "旧密码错误";
        }
        int updateCount = userMapper.updatePassword(MD5Util.MD5EncodeUtf8(passwordNew),mallUserVO.getId());
        if(updateCount > 0){
            return ServiceResultEnum.SUCCESS.getResult();
        }
        return "密码修改失败";
    }

}
